package com.cnpinxi.controller.admin.user;

import com.cnpinxi.controller.base.BaseController;
import com.cnpinxi.def.Constant;
import com.cnpinxi.domain.User;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import com.cnpinxi.result.ResultObj;
import com.cnpinxi.service.AdminUserService;
import com.cnpinxi.service.MenuService;
import com.cnpinxi.service.RoleService;
import com.cnpinxi.service.UserService;
import com.cnpinxi.tool.HttpUtils;
import com.cnpinxi.tool.excel.ExportExcel;
import com.cnpinxi.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Andrew  on 2017/2/26.
 */
@Controller
@RequestMapping(value = "/admin/customer")
public class CustomerController extends BaseController {
    /*@Autowired
    RedisCache redisCache;*/
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    AdminUserService adminUserService;    @Autowired
    UserService userService;










    /**
     * 跳转到修改页面
     *
     * @param request
     * @param tid
     * @return
     */
    @RequestMapping(value = "/updatePassWord")
    @ResponseBody
    public ModelAndView updatePassWord(HttpServletRequest request, Integer tid) {
        Map<String, String> map = this.showRequestParameters(request);
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/admin/user/change-password");
        mov.addObject("map",map);
        return mov;
    }

    /**
     * 用户列表
     * @param request
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/getCustomerList")
    public ModelAndView getCustomerList(HttpServletRequest request, Integer page, Integer pageSize) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/admin/user/getCustomerList");
        if (page == null || page == 0) {
            page = Constant.PAGENUM;
        }
        // 设置每页记录数
        if (pageSize == null || pageSize == 0) {
            pageSize = Constant.PAGESIZENum;
        }

        Map<String, String> map = this.showRequestParameters(request);
        map.put("page",String.valueOf(page));
        map.put("pageSize",String.valueOf(pageSize));
        PageHelper.startPage(page, pageSize);
        List<User> userList = userService.getUserList(map);

        PageInfo<User> pageinfo = new PageInfo<User>(userList);
        mov.addObject("pageinfo", pageinfo);
        mov.addObject("bean", map);
        return mov;

    }


    /**
     * 导出用户到Excel表
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("getCustomerListForExcel")

    public ResponseEntity<byte[]> organization(HttpServletRequest request,
                                               HttpServletResponse response) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        String fileName = "用户列表";
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", HttpUtils.encode(request, fileName + ".xls"));
        List<User> userList = userService.getUserList(this.showRequestParameters(request));
        List<LinkedHashMap<String, Object>> list = new ArrayList<>();
        for (User user:userList) {
            LinkedHashMap<String, Object> lmap = new LinkedHashMap<>();
            lmap.put("userId", user.getTid());
            lmap.put("userName", user.getUserName());
            lmap.put("phone", user.getPhone());
            lmap.put("openId", user.getOpenId());
            lmap.put("address", user.getUserAddress());
            lmap.put("sourceQRCode", user.getSourceQRCode());
            lmap.put("userType", user.getUserType()==1?"经理":"普通");
            lmap.put("createTime", DateUtil.dateToStr(user.getCreateTime(), DateUtil.DATE_TIME));
            list.add(lmap);
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        ExportExcel<LinkedHashMap<String, Object>> ex = new ExportExcel<LinkedHashMap<String, Object>>();
        String[] headers1 = {"用户Id","姓名", "电话", "openId","地址","分销二维码地址", "类型", "注册时间"};
        //ex.ExportExcel(fileName, ExcelType.HSSF, headers1, list, os);
        ex.exportExcel(fileName, ExcelType.HSSF, headers1, list, os);
        os.flush();
        return new ResponseEntity<byte[]>(os.toByteArray(), headers, HttpStatus.CREATED);
    }


    @RequestMapping(value = "/modifyCustomerInfo")
    public ModelAndView modifyCustomerInfo(Long userId) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/admin/user/modifyCustomerInfo");
        User  user = userService.getUserById(userId);
        mov.addObject("user", user);
        return mov;

    }

    /**
     * 修改后台用户信息
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/modifyCustomer",  method = RequestMethod.POST)
    @ResponseBody
    public String modifyUser(User user) {

        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_FAIL);
        try {
            System.out.println("getUserType=======================>>>>>>>>>>>>>>>>>>"+user.getUserType());
          userService.modifyUser(user);
            resultObj.setCode(ResultObj.CODE_SUCCESS);
            resultObj.setMsg("成功！");
        } catch (MyRunTimeExcption myRunTimeExcption) {
            resultObj.setMsg(myRunTimeExcption.getMessage());
            myRunTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }



}
